package com.linln.frontend.controller;


import cn.hutool.core.util.StrUtil;

import com.linln.common.utils.CaptchaUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.ToolUtil;
import com.linln.common.vo.ResultVo;
import com.linln.component.email.Email;
import com.linln.component.email.MailServiceUtil;
import com.linln.modules.system.domain.Comment;

import com.linln.modules.system.repository.ArticleRepository;

import com.linln.modules.system.repository.CommentRepository;
import com.linln.modules.system.repository.ParamRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.Context;

import javax.servlet.http.HttpServletRequest;

import java.util.*;


import static com.linln.common.constant.ParamConst.ALL_COMMENT_OPEN;
import static com.linln.common.constant.ParamConst.COMMENT_KEYWORD;
import static com.linln.common.constant.ParamConst.IS_OPEN_MESSAGE;

@Controller("fontCommentController")
@RequestMapping("frontend")
public class CommentController {
    @Autowired
    private CommentRepository commentRepository;
   // private  KeywordRepository keywordRepository;
    @Autowired
    private ParamRepository paramRepository;
    @Autowired
    private ArticleRepository articleRepository;
   // private CateRepository cateRepository;
    @Autowired
    private MailServiceUtil mailService;


    @PostMapping("/comment/sub")
    @ResponseBody
    public ResultVo sub(@RequestBody Comment comment, BindingResult bindingResult, HttpServletRequest request) {
        final String initSure = "1";
        ResultVo resultVo= ResultVoUtil.ajaxDone(
                () -> initSure.equals(paramRepository.findFirstByName(ALL_COMMENT_OPEN).getValue()) && articleRepository.getOne(comment.getArticle().getId()).getCommented(),
                () -> {
                    if (!bindingResult.hasErrors()) {
                        comment.setIpAddr(ToolUtil.getRemoteAddress(request));

                        try {
                            comment.setIpCnAddr(ToolUtil.getIpInfo(comment.getIpAddr()));
                        }catch (Exception e)
                        {
                            comment.setIpCnAddr("未知星球的");
                            e.printStackTrace();
                        }
                        comment.setUserAgent(request.getHeader("user-agent"));
                        comment.setComment(ToolUtil.stripSqlXSS(comment.getComment()));

                        //List<NBKeyword> keywords = keywordRepository.findAll();
                        String  keyword =  paramRepository.findFirstByName(COMMENT_KEYWORD).getValue();
                        String[] keywords = keyword.split("|");
                        Arrays.stream(keywords).forEach(kw -> comment.setComment(comment.getComment().replace(kw, StrUtil.repeat("*", kw.length()))));
                        return ResultVoUtil.ajaxDone(commentRepository::save, comment, "发表评论成功", "发表评论失败");
                    } else {
                        return ResultVoUtil.ajaxJsr303(bindingResult.getFieldErrors());
                    }
                },
                () -> "未开放评论功能，请勿非法操作！"
        );

        if (resultVo.getCode() == 200){
            new Thread( ()->{
                Email email= Email.builder().comment(comment.getComment()).subject("回复评论").to("1343453657@qq.com").build();
                //   mailService.sendMsgMail(email);
                Context ctx = new Context();
                email.setTemplate("/emailCommend");
                mailService.sendMsgMail(email);
                commentRepository.findById(comment.getParentId()).ifPresent(k->{
                    if (!StringUtils.isEmpty(k.getCreateBy().getEmail())){
                        email.setTo(k.getCreateBy().getEmail());
                        ctx.setVariable("comment",comment.getComment());
                        ctx.setVariable("userName",k.getCreateBy().getNickname());
                        ctx.setVariable("commentUrl",k.getComment());

                        mailService.htmlEmail(ctx,email);
                    }
                });
            }).start();
        }
        return  resultVo;
    }
    @PostMapping("/message/sub")
    @ResponseBody
    public ResultVo subs(@RequestBody Comment comment, BindingResult bindingResult, HttpServletRequest request) {
        final String initSure = "1";
        ResultVo resultVo= ResultVoUtil.ajaxDone(
                () -> initSure.equals(paramRepository.findFirstByName(IS_OPEN_MESSAGE).getValue()),
                () -> {
                    if (!bindingResult.hasErrors()) {
                        comment.setIpAddr(ToolUtil.getRemoteAddress(request));

                        try {
                            comment.setIpCnAddr(ToolUtil.getIpInfo(comment.getIpAddr()));
                        }catch (Exception e)
                        {
                            comment.setIpCnAddr("未知星球的");
                            e.printStackTrace();
                        }
                        comment.setUserAgent(request.getHeader("user-agent"));
                        comment.setComment(ToolUtil.stripSqlXSS(comment.getComment()));

                        //List<NBKeyword> keywords = keywordRepository.findAll();
                        String  keyword =  paramRepository.findFirstByName(COMMENT_KEYWORD).getValue();
                        String[] keywords = keyword.split("|");
                        Arrays.stream(keywords).forEach(kw -> comment.setComment(comment.getComment().replace(kw, StrUtil.repeat("*", kw.length()))));
                        return ResultVoUtil.ajaxDone(commentRepository::save, comment, "发表留言成功", "发表留言失败");
                    } else {
                        return ResultVoUtil.ajaxJsr303(bindingResult.getFieldErrors());
                    }
                },
                () -> "未开放评论功能，请勿非法操作！"
        );
        if (resultVo.getCode() == 200){
            new Thread( ()->{
                Email email= Email.builder().comment(comment.getComment()).subject("回复留言").to("1343453657@qq.com").build();
                 //   mailService.sendMsgMail(email);
                   Context ctx = new Context();
                  email.setTemplate("/emailCommend");
                  mailService.sendMsgMail(email);
                  commentRepository.findById(comment.getParentId()).ifPresent(k->{
                      if (!StringUtils.isEmpty(k.getCreateBy().getEmail())){
                          email.setTo(k.getCreateBy().getEmail());
                          ctx.setVariable("comment",comment.getComment());
                          ctx.setVariable("userName",k.getCreateBy().getNickname());
                          ctx.setVariable("commentUrl",k.getComment());
                          mailService.htmlEmail(ctx,email);
                      }
                  });
            }).start();
        }
        return  resultVo;
    }
//    @RequestMapping("/mymessqge")
//    public String myMessage(HttpServletRequest request, Model model)
//    {
//        NBSysUser user=NBUtils.getSessionUser();
//        model.addAttribute("cateList", cateRepository.findAll());
//        if (user!=null) {
//          List<NBComment> list = commentRepository.findNBCommentsByUseredId(user.getId());
//            model.addAttribute("comments",list);
//            commentRepository.updateReadeByReadeAndUseredId(user.getId(),false);
//        }
//        return "frontend/mymessage";
//    }
    /**
     * 发送邮件验证码
     */
    @GetMapping("/emailCode")
    @ResponseBody
    public ResultVo emailCode(HttpServletRequest request,String to){
        // 获取验证码
        String code = CaptchaUtil.getRandomCode();
        Email email = Email.builder().subject("用户邮箱验证").to(to).template("/emailCode").build();
        Context ctx = new Context();
        ctx.setVariable("code",code);
        // 将验证码输入到session中，用来验证
        request.getSession().setMaxInactiveInterval(20*60);
        request.getSession() .setAttribute("emailCode", code);
        request.getSession() .setAttribute("emailCodeTo", to);
        Map<String, Long> map =new HashMap<>();
        Calendar calender = Calendar.getInstance();
        map.put("serverTime",calender.getTime().getTime());
        calender.add(Calendar.MINUTE,1);
        map.put("endTime",calender.getTime().getTime());
        mailService.htmlEmail(ctx,email);
        return ResultVoUtil.success("发送成功，请查收！",map);
    }
}
